package com.cskaoyan.controller.promote;

import com.cskaoyan.bean.MallStorage;
import com.cskaoyan.model.vo.BaseRespVo;
import com.cskaoyan.model.vo.fileupload.FileUploadData;
import com.cskaoyan.service.system.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * 微信端 反馈 图片上传
 * @author：23117
 * @date: 2021/12/4
 */
@RestController
@RequestMapping("wx/storage")
public class WxStorageController {
    @Value("${upload.path}")
    String path;

    @Autowired
    StorageService storageService;

    @RequestMapping("upload")
    public BaseRespVo upload(HttpServletRequest httpServletRequest, MultipartFile file) throws IOException {
        //           原始上传文件名
        String originalFileName = file.getOriginalFilename();//name
        //           获取文件格式
        String contentType = file.getContentType();//type
        //           获取文件大小
        int fileSize = ((int) file.getSize());//size
        //文件创建时间
        Date now = new Date();
        //获取url
        String storageFileName = UUID.randomUUID().toString().replace("-", "");
        if (new File(path).mkdirs()) {
            new File(path).mkdirs();
        }
        //生成文件地址
        File storageFile = new File(path, storageFileName + ".jpg");

        //注入
        file.transferTo(storageFile);
        FileUploadData fileUploadData = new FileUploadData(null, storageFileName, originalFileName, contentType, fileSize,
                //httpServletRequest.getRequestURL().toString()+"/"+storageFileName + ".jpg"
                //注意这里是localAddr()本地IP地址,而非是获取客户端地址RemoteAddr
                httpServletRequest.getRequestURL().toString().replace(httpServletRequest.getRequestURI(),"")
//                    "http://"+httpServletRequest.getRemoteHost()+":8083"
                        + "/wxhomeindex/storage/fetch/"+storageFileName+".jpg"
                , now, now);
        MallStorage storage = storageService.uploadPic(fileUploadData);
        return BaseRespVo.ok(storage);

    }
}
